<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>城市运输分析测试</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
      background-color: #f5f5f5;
    }

    .container {
      background-color: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    h1 {
      color: #333;
      text-align: center;
      margin-bottom: 30px;
    }

    .form-group {
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #555;
    }

    input,
    select,
    button {
      width: 100%;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    button {
      background-color: #007bff;
      color: white;
      border: none;
      cursor: pointer;
      font-weight: bold;
      margin-top: 10px;
    }

    button:hover {
      background-color: #0056b3;
    }

    button:disabled {
      background-color: #6c757d;
      cursor: not-allowed;
    }

    .btn-secondary {
      background-color: #6c757d;
    }

    .btn-secondary:hover {
      background-color: #545b62;
    }

    .result-container {
      margin-top: 30px;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 4px;
      border-left: 4px solid #007bff;
    }

    .error {
      color: #dc3545;
      border-left-color: #dc3545;
    }

    .success {
      color: #28a745;
      border-left-color: #28a745;
    }

    .warning {
      color: #ffc107;
      border-left-color: #ffc107;
    }

    .city-info {
      background-color: white;
      padding: 15px;
      margin: 10px 0;
      border-radius: 4px;
      border: 1px solid #dee2e6;
    }

    .stat-row {
      display: flex;
      justify-content: space-between;
      margin: 5px 0;
    }

    .stat-label {
      font-weight: bold;
    }

    .loading {
      text-align: center;
      color: #666;
    }

    .form-row {
      display: flex;
      gap: 20px;
    }

    .form-row .form-group {
      flex: 1;
    }

    @media (max-width: 768px) {
      .form-row {
        flex-direction: column;
        gap: 0;
      }
    }

    .cities-list {
      background-color: #e9ecef;
      padding: 10px;
      border-radius: 4px;
      margin-top: 10px;
      max-height: 150px;
      overflow-y: auto;
    }

    .city-tag {
      display: inline-block;
      background-color: #007bff;
      color: white;
      padding: 3px 8px;
      margin: 2px;
      border-radius: 12px;
      font-size: 12px;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>🚛 城市运输分析测试工具</h1>

    <div class="form-row">
      <div class="form-group">
        <label for="departureCity">出发地城市：</label>
        <input type="text" id="departureCity" placeholder="请输入出发地城市名，如：北京" />
      </div>
      <div class="form-group">
        <label for="destinationCity">目的地城市：</label>
        <input type="text" id="destinationCity" placeholder="请输入目的地城市名，如：上海" />
      </div>
    </div>

    <div class="form-group">
      <button onclick="analyzeCityTransit()">🔍 分析城市运输</button>
    </div>

    <div class="form-row">
      <div class="form-group">
        <button class="btn-secondary" onclick="loadAvailableCities()">📍 获取可用城市列表</button>
      </div>
      <div class="form-group">
        <button class="btn-secondary" onclick="runTestCases()">🧪 运行测试用例</button>
      </div>
    </div>

    <div id="result"></div>
  </div>

  <script>
    // API 基础路径
    const BASE_URL = 'http://localhost:8080/pack/locationLog';

    // 获取可用城市列表
    async function loadAvailableCities () {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML = '<div class="loading">正在获取城市列表...</div>';

      try {
        const response = await fetch(`${BASE_URL}/analysis/cities`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          }
        });

        const data = await response.json();

        if (data.code === 200) {
          const cities = data.data;
          let html = `
                        <div class="result-container success">
                            <h3>📍 可用城市列表 (共 ${cities.length} 个)</h3>
                            <div class="cities-list">
                    `;

          cities.forEach(city => {
            html += `<span class="city-tag">${city}</span>`;
          });

          html += `
                            </div>
                            <p style="margin-top: 15px; color: #666; font-size: 14px;">
                                💡 提示：点击任意城市名称可以快速填入输入框
                            </p>
                        </div>
                    `;

          resultDiv.innerHTML = html;

          // 为城市标签添加点击事件
          document.querySelectorAll('.city-tag').forEach(tag => {
            tag.style.cursor = 'pointer';
            tag.onclick = function () {
              const departure = document.getElementById('departureCity');
              const destination = document.getElementById('destinationCity');

              if (!departure.value) {
                departure.value = this.textContent;
              } else if (!destination.value) {
                destination.value = this.textContent;
              } else {
                departure.value = this.textContent;
                destination.value = '';
              }
            };
          });

        } else {
          resultDiv.innerHTML = `<div class="result-container error">❌ 获取城市列表失败：${data.msg}</div>`;
        }
      } catch (error) {
        resultDiv.innerHTML = `<div class="result-container error">❌ 网络错误：${error.message}</div>`;
      }
    }

    // 分析城市运输
    async function analyzeCityTransit () {
      const departureCity = document.getElementById('departureCity').value.trim();
      const destinationCity = document.getElementById('destinationCity').value.trim();
      const resultDiv = document.getElementById('result');

      // 参数验证
      if (!departureCity) {
        resultDiv.innerHTML = '<div class="result-container error">❌ 请输入出发地城市名</div>';
        return;
      }

      if (!destinationCity) {
        resultDiv.innerHTML = '<div class="result-container error">❌ 请输入目的地城市名</div>';
        return;
      }

      if (departureCity === destinationCity) {
        resultDiv.innerHTML = '<div class="result-container error">❌ 出发地和目的地不能相同</div>';
        return;
      }

      resultDiv.innerHTML = '<div class="loading">🔄 正在分析运输数据，请稍候...</div>';

      try {
        const url = `${BASE_URL}/analysis/cityTransit?departureCity=${encodeURIComponent(departureCity)}&destinationCity=${encodeURIComponent(destinationCity)}`;
        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          }
        });

        const data = await response.json();

        if (data.code === 200) {
          displayAnalysisResult(data.data);
        } else if (data.code === 601) {
          resultDiv.innerHTML = `<div class="result-container warning">⚠️ ${data.msg}</div>`;
        } else {
          resultDiv.innerHTML = `<div class="result-container error">❌ 分析失败：${data.msg}</div>`;
        }
      } catch (error) {
        resultDiv.innerHTML = `<div class="result-container error">❌ 网络错误：${error.message}</div>`;
      }
    }

    // 显示分析结果
    function displayAnalysisResult (result) {
      const resultDiv = document.getElementById('result');

      let html = `
                <div class="result-container success">
                    <h3>📊 城市运输分析结果</h3>

                    <div class="city-info">
                        <h4>🛣️ 基本信息</h4>
                        <div class="stat-row">
                            <span class="stat-label">出发地：</span>
                            <span>${result.departureCity}</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">目的地：</span>
                            <span>${result.destinationCity}</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">参与计算的运单数：</span>
                            <span>${result.wayBillCount} 个</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">平均运输时间：</span>
                            <span>${result.totalTransitTime} 小时</span>
                        </div>
                    </div>
            `;

      if (result.passedCities && result.passedCities.length > 0) {
        html += `
                    <div class="city-info">
                        <h4>🏙️ 经过城市详情 (共 ${result.passedCities.length} 个城市)</h4>
                `;

        result.passedCities.forEach((city, index) => {
          html += `
                        <div style="background-color: #f8f9fa; padding: 10px; margin: 8px 0; border-radius: 4px;">
                            <div class="stat-row">
                                <span class="stat-label">第${city.passOrder}站: ${city.cityName}</span>
                                <span>到下一城市平均用时：${city.averageStayTime} 小时</span>
                            </div>
                        </div>
                    `;
        });

        html += '</div>';
      }

      html += '</div>';
      resultDiv.innerHTML = html;
    }

    // 运行测试用例
    async function runTestCases () {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML = '<div class="loading">🧪 正在运行测试用例...</div>';

      try {
        const response = await fetch(`${BASE_URL}/test/cityTransit`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          }
        });

        const data = await response.json();

        if (data.code === 200) {
          displayTestResults(data.data);
        } else {
          resultDiv.innerHTML = `<div class="result-container error">❌ 测试失败：${data.msg}</div>`;
        }
      } catch (error) {
        resultDiv.innerHTML = `<div class="result-container error">❌ 网络错误：${error.message}</div>`;
      }
    }

    // 显示测试结果
    function displayTestResults (testData) {
      const resultDiv = document.getElementById('result');

      let html = `
                <div class="result-container success">
                    <h3>🧪 测试用例结果 (共 ${testData.testCases} 个)</h3>
            `;

      testData.results.forEach((result, index) => {
        const statusIcon = result.success ? '✅' : '❌';
        const statusClass = result.success ? 'success' : 'error';

        html += `
                    <div class="city-info">
                        <h4>${statusIcon} 测试 ${index + 1}: ${result.departure} → ${result.destination}</h4>
                `;

        if (result.success) {
          html += `
                        <div class="stat-row">
                            <span class="stat-label">运单数量：</span>
                            <span>${result.wayBillCount} 个</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">平均运输时间：</span>
                            <span>${result.totalTransitTime} 小时</span>
                        </div>
                        <div class="stat-row">
                            <span class="stat-label">经过城市数：</span>
                            <span>${result.passedCities ? result.passedCities.length : 0} 个</span>
                        </div>
                    `;
        } else {
          html += `
                        <div class="stat-row" style="color: #dc3545;">
                            <span class="stat-label">错误信息：</span>
                            <span>${result.error}</span>
                        </div>
                    `;
        }

        html += '</div>';
      });

      html += '</div>';
      resultDiv.innerHTML = html;
    }

    // 页面加载时自动获取城市列表
    window.onload = function () {
      loadAvailableCities();
    };

    // 添加回车键支持
    document.getElementById('departureCity').addEventListener('keypress', function (e) {
      if (e.key === 'Enter') {
        document.getElementById('destinationCity').focus();
      }
    });

    document.getElementById('destinationCity').addEventListener('keypress', function (e) {
      if (e.key === 'Enter') {
        analyzeCityTransit();
      }
    });
  </script>
</body>

</html>